package au.com.betaversion;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import au.com.betaversion.domain.Aircraft;
import au.com.betaversion.domain.DatabaseInfo;
import au.com.betaversion.repository.AircraftRepository;
import au.com.bytecode.opencsv.CSVReader;

@Controller
@RequestMapping(value = "/aircraft")
public class AircraftController {

	@Autowired
	private AircraftRepository aircraftRepository;
	
	@RequestMapping(method = RequestMethod.GET)
	public String aircraft(Model model) {
		model.addAttribute("aircraft", new Aircraft());
		return "aircraft";
	}
	
	@RequestMapping(value="/add", method = RequestMethod.POST)
	public String aircraftPost(@ModelAttribute("aircraft") Aircraft aircraft) {
		aircraftRepository.save(aircraft);
		return "redirect:/aircraft";
	}
	
	@RequestMapping(value = "casa", method = RequestMethod.GET)
	public String loadFromUrl(Model model) {
		File file = null;
		CSVReader csvReader = null;
		
		try {
			file = new File("/tmp/temp_download");
			FileUtils.copyURLToFile(new URL("http://casa.gov.au/wcmswr/asp/casadata/register/data/ACRFTREG.CSV"), file);
			csvReader = new CSVReader(new FileReader(file), ',');
			String [] nextLine;
		    while ((nextLine = csvReader.readNext()) != null) {
	    		Aircraft aircraft = new Aircraft();
	    		if(nextLine[0].equals(""))
	    			continue;
	    		aircraft.setMark("VH-" + nextLine[0]);
	    		aircraft.setManufacturer(nextLine[1]);
	    		aircraft.setModel(nextLine[3]);
	    		aircraft.setOperatorName(nextLine[20]);
	    		aircraft.setSerialNumber(nextLine[4]);
	    		aircraft.setOperatorState(nextLine[24]);
	    		aircraft.setMtow(nextLine[5]);
	    		aircraftRepository.save(aircraft);
		    }
		    DatabaseInfo.lastDatabaseUpdate = new Date();
		} catch (FileNotFoundException e) {
			model.addAttribute("error", e.getMessage());
			return "aircraft/list";
		} catch (IOException e) {
			model.addAttribute("error", e.getMessage());
			return "aircraft/list";
		} catch(Exception e){
			model.addAttribute("error", e.getCause());
			return "aircraft/list";
		} finally {
			file.delete();
			try {
				if(csvReader != null)
					csvReader.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return "redirect:/aircraft";
	}
	
	@RequestMapping(value = "/details", method = RequestMethod.POST)
	public @ResponseBody Aircraft getDeatils(@RequestParam("mark") String mark) {
		Aircraft aircraft = aircraftRepository.findOne(mark.toUpperCase());
		if(aircraft != null)
			return aircraft;
		return null;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Model model) {
		List<Aircraft> aircrafts = aircraftRepository.findAll();
		Collections.sort(aircrafts);
		model.addAttribute("aircrafts", aircrafts);
		return "aircraft/list";
	}
	
	@RequestMapping(value = "/delete/{mark}", method = RequestMethod.GET)
	public String list(@PathVariable("mark") String mark, Model model) {
		aircraftRepository.delete(mark);
		return "redirect:/aircraft/list";
	}
	
}
